import { pick } from '../../util';
import { HttpHeaders, HttpParams } from '@angular/common/http';


/**
 * 基于后台查询接口入参和返回值，抽象出来的查询类
 */
export class Query<U> {
  /** 保存查询项 */
  params: any = {};
  metadataMap: any;
  /** 分页数据 start === skip */
  page: { size: number, start: number, skip: number } = { size: 20, start: 1, skip: 1 };
  /** 排序字段 */
  sorts: { field: string, type: string }[];

  /**
   *  查询url，序列化时排除
   */
  url: U;
  /**
   * 保存url地址部分的参数，序列化时排除
   * 示例 /order/:id urlParams = {id: 11} ==> /order/11
   */
  urlParams: any = {};
  httpOptions: {
    headers?: HttpHeaders | {
      [header: string]: string | string[];
    };
    observe?: 'body';
    params?: HttpParams | {
      [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType: 'json';
    withCredentials?: boolean;
  } = { responseType: 'json' };

  /**
   * 缓存请求数据，只对 get 请求有效
   */
  _cache = false;
  /**
   * 请求时显示loading遮罩层
   */
  _loading: string | boolean = false;
  /**
   * 是否禁用默认请求异常提示框
   */
  _noEmitOnError = false;
  /**
   * 将Query对象转换为后台查询接口可以接收的数据格式
   */
  serialize() {
    const params = pick(this, '** -url -urlParams');
    return Object.assign(params, this.urlParams);
  }

  /**
   * 根据dataGrid参数设置Query内部变量
   */
  parseForDev(loadOptions: any) {
    if (Array.isArray(loadOptions.sort) && loadOptions.sort.length) {
      this.sorts = [];
      loadOptions.sort.forEach((s) => {
        this.sorts.push({
          field: s.selector,
          type: s.desc ? 'desc' : 'asc'
        });
      });
    }

    if (Number.isInteger(loadOptions.take)) {
      this.page.size = loadOptions.take;
    }
    if (Number.isInteger(loadOptions.skip)) {
      this.page.start = loadOptions.skip;
      this.page.skip = loadOptions.skip;
    }
  }
}
